package data.join.com.media;

import android.content.Context;
import android.text.TextUtils;

import java.io.IOException;
import java.util.List;

import data.join.com.database.bean.FileUpload;
import data.join.com.database.bean.FileUploadPref;
import data.join.com.database.bean.VideoBean;
import data.join.com.database.bean.VideoDBPref;
import data.join.com.network.RetrofitManager;
import data.join.com.network.gson.FileNameUploadResponse;
import data.join.com.network.gson.LockFileUpload;
import data.join.com.service.MainService;
import data.join.com.utils.BaseThread;
import data.join.com.utils.FileUtils;
import data.join.com.utils.MyDate;
import data.join.com.utils.MyLog;
import data.join.com.utils.QiniuApi;
import data.join.com.utils.QuickShPref;
import data.join.com.utils.WakeLockUtils;
import retrofit2.Call;
import retrofit2.Response;


/**
 * Created by huyongming on 2016/4/21.
 */
public class VideoUploadThread extends BaseThread {
    public  boolean running = true;
    private static final String TAG = VideoUploadThread.class.getSimpleName();
    private Context mContext;

    private static VideoUploadThread videoUploadThread;

    private VideoUploadThread(Context context){
        this.mContext = context;
    }

    public static VideoUploadThread getInstance(Context context){
        if(videoUploadThread == null){
            videoUploadThread = new VideoUploadThread(context);
        }
        return videoUploadThread;
    }

    @Override
    public void run() {
        super.run();

        while (running){

            if(QuickShPref.getInstance().getBoolean(QuickShPref.LockVideoEnable)) {
                //上传事件相关的视频资料
                if (MainService.isNetWorkConnect(mContext, TAG)) {
                    WakeLockUtils.getDefault(mContext).acquireWakeLock(TAG);
                    uploadVideo();
                    WakeLockUtils.getDefault(mContext).releaseWakeLock(TAG);
                }
            }else{
                MyLog.D(TAG,"LockVideoEnable is False");
            }
            await(TIME_WAIT);
        }
    }

    private void uploadVideo() {
        List<FileUpload> list = FileUploadPref.getInstance().queryUnLoadVideo();
        MyLog.D(TAG,"uploadVideo list.size()="+list.size());
        if(list != null){
            for (FileUpload fileUpload:list){

                if (QuickShPref.getInstance().getBoolean(QuickShPref.LockVideoEnable)) {

                    if (uploadFile(fileUpload)) {

                    } else {
                        break;
                    }
                }else{
                    MyLog.D(TAG,"LockVideoEnable is False,break");
                    break;
                }
            }
        }
    }

    private boolean uploadFile(FileUpload fileUpload){
        boolean ret = false;
        VideoBean videoBean = VideoDBPref.getInstance().getVideoById(fileUpload.mediaId);

        if(videoBean != null){
            if(TextUtils.isEmpty(fileUpload.cloudKey)) {
                QiniuApi.UploadResult uploadResult = QiniuApi.getDefault().startUploadAsync(videoBean.srcPath, QiniuApi.getQiniuToken(videoBean.srcPath,"video"));
                if(uploadResult != null) {
                    fileUpload.cloudKey = uploadResult.cloudKey;
                    fileUpload.persistentId = uploadResult.persistentId;
                    FileUploadPref.getInstance().updateFileUpload(fileUpload);
                    MyLog.D(TAG,"uploadFile success:cloudKey="+fileUpload.cloudKey);
                }else{
                    MyLog.D(TAG,"uploadFile fail:uploadResult is NULL");
                }
            }

            if(!TextUtils.isEmpty(fileUpload.cloudKey)){
                if(uploadFileName(fileUpload,videoBean)){
                    MyLog.D(TAG,"uploadFileName success");
                    fileUpload.status = FileUploadPref.STATUS_UPLOAD_SUCCESS;
                    FileUploadPref.getInstance().updateFileUpload(fileUpload);
                    ret = true;
                }else{
                    MyLog.D(TAG,"uploadFileName fail");
                }
            }else{
                MyLog.D(TAG,"fileUpload.cloudKey is NULL");
            }
        }else{
            MyLog.D(TAG,"uploadFile error:videoBean is NULL");
            fileUpload.status = FileUploadPref.STATUS_UPLOAD_ERROR;
            FileUploadPref.getInstance().updateFileUpload(fileUpload);
            ret = true;
        }
        return ret;
    }

    private boolean uploadFileName(FileUpload fileUpload,VideoBean videoBean){
        boolean ret = false;
        LockFileUpload lockFileUpload = new LockFileUpload();
        lockFileUpload.imei = QuickShPref.getInstance().getString(QuickShPref.DeviceImei);
        lockFileUpload.begin_at = MyDate.getFormatTimeByLong(videoBean.startTime);
        lockFileUpload.end_at = MyDate.getFormatTimeByLong(videoBean.endTime);
        lockFileUpload.key = fileUpload.cloudKey;
        lockFileUpload.persist_id = fileUpload.persistentId;
        lockFileUpload.resource_id = videoBean.id;
        lockFileUpload.fsize = FileUtils.getFileSize(videoBean.srcPath);

        Call<FileNameUploadResponse> responseCall = RetrofitManager.getApiService().uploadLockVideo(RetrofitManager.getBodyByJson(lockFileUpload));

        try {
            Response<FileNameUploadResponse> response =  responseCall.execute();

            if(response.isSuccessful()){

                FileNameUploadResponse fileNameUploadResponse = response.body();

                if(fileNameUploadResponse != null && fileNameUploadResponse.isAvail()) {
                    ret = true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ret;
    }

}
